package psn.zjk.elasticsearch;

import org.apache.http.HttpHost;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;

@Component
public class ElasticsearchClient {

    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchClient.class);

    public void request() throws IOException {
        String ip = "127.0.0.1";
        int port = 9200;
        String protocal = "http";
        RestClient client = RestClient.builder(new HttpHost(ip, port, protocal), new HttpHost(ip, 9201, protocal))
                .build();
        Request get = new Request("GET", "/");
        get.addParameter("pretty", "true");
        //        get.setJsonEntity();
        Response response = client.performRequest(get);
        client.close();
        logger.info(EntityUtils.toString(response.getEntity()));

    }

    @PostConstruct
    public void start() {
        System.out.println(1111);
        new Thread(() -> {
            while (true) {
                try {
                    request();
                    Thread.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
